import { useEffect, useRef } from 'react'
import { useModelStore } from '@/stores'

/**
 *转换文件流
 */
function convertBufferToBlobUrl(buffer: Uint8Array): string {
  const uint8Array = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer)
  const arrayBuffer =
    uint8Array.buffer instanceof ArrayBuffer
      ? uint8Array.buffer.slice(
          uint8Array.byteOffset,
          uint8Array.byteOffset + uint8Array.byteLength
        )
      : (uint8Array.buffer as unknown as ArrayBuffer)
  const blob = new Blob([arrayBuffer])
  return URL.createObjectURL(blob)
}

type ModelFileData =
  | { path: string; buffer: Uint8Array }
  | Uint8Array
  | string

/**
 * 监听Electron，自动加载模型文件
 * 
 */
export function useModelFile() {
  
  const blobUrlsRef = useRef<Set<string>>(new Set())

  useEffect(() => {
    const handleModelFileSelected = (
      _event: unknown,
      data: ModelFileData
    ) => {
      console.log('🚀 ~ handleModelFileSelected ~ data:', data)

      try {
        let blobUrl: string | null = null
        let originalPath: string | null = null
        let buffer: Uint8Array | null = null

        // 处理不同类型的数据
        if (data && typeof data === 'object' && 'buffer' in data) {
       
          const fileData = data as { path: string; buffer: Uint8Array }
          buffer = fileData.buffer
          originalPath = fileData.path
        } else if (data && typeof data === 'object' && ArrayBuffer.isView(data)) {
      
          buffer = data as Uint8Array
        } else if (typeof data === 'string') {
       
          useModelStore.getState().addModel(data, data)
          return
        }

       
        if (buffer) {
          blobUrl = convertBufferToBlobUrl(buffer)
       
          blobUrlsRef.current.add(blobUrl)
          console.log('🚀 ~ 创建的 Blob URL:', blobUrl)
       
         
          useModelStore.getState().addModel(blobUrl, originalPath || '未命名文件')
        } else {
          useModelStore.getState().setError('无效的文件数据格式')
        }
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : '加载文件时发生未知错误'
        console.error('处理模型文件时出错:', error)
        useModelStore.getState().setError(errorMessage)
      }
    }

    if (window.ipcRenderer) {
      window.ipcRenderer.on('model-file-selected', handleModelFileSelected)


      const blobUrlsSet = blobUrlsRef.current

      return () => {
        window.ipcRenderer?.off('model-file-selected', handleModelFileSelected)
       
        const urls = Array.from(blobUrlsSet)
        urls.forEach((url) => {
          URL.revokeObjectURL(url)
        })
        blobUrlsSet.clear()
      }
    }
  }, []) 
}
